package cc.customer.web.aiResource;

import cc.customer.aiEmport.damain.CAiEmp;
import cc.customer.aiEmport.damain.CAiEmpImport;
import cc.customer.aiEmport.services.AiEmpServices;
import cc.customer.bigEmport.damain.BigEmp;
import cc.customer.bigEmport.damain.EpRecords;
import cc.customer.bigEmport.damain.EprRecords;
import cc.customer.bigEmport.dao.EprRecordsMapper;
import cc.customer.common.domain.QueryRequest;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.DateUtil;
import cc.customer.common.utils.FileUtils;
import cc.customer.common.utils.Utils;
import cc.customer.expCustomer.services.ExEmpServices;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import cc.customer.web.sys.controller.base.BaseController;
import cc.customer.web.util.AIReadExcel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Description: customer
 * Created by yhsh on 2020/3/24 9:38
 * version 2.0
 * 方法说明
 */
@Controller
@RequestMapping("/aiEpResoure")
public class AiEpResourceController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AiEpResourceController.class);

	@Autowired
	private AiEmpServices aiEmpServices;

	@Autowired
	private UserService userService;

	@Autowired
	private ExEmpServices exEmpServices;

	@Autowired
	private EprRecordsMapper recordsMapper;


	/**加载AI名单主页**/
	@RequestMapping(value="/aiIndex")
	public String loadBigEpResoureIndex (){
		return "customer/aiEpResource/aiEpResource/aiEpResoure_index";
	}

	/**新增客户**/
	@RequestMapping(value = "/addCustomerDialog")
	public String addCustomerDialog(){return "customer/aiEpResource/aiEpResource/aicustomer_emp";}
	/**新增批次**/
	@RequestMapping(value = "/aipoIndex")
	public String addCustomerDao(){return "customer/aiEpResource/aiEpExport/aoEpExport_index";}
	/**aireIndex 导出记录**/
	@RequestMapping(value = "/aireIndex")
	public String aireIndex(){return "customer/aiEpResource/aiEpScreen/aiScreen_index";}
	/**加载详情页面**/
	@RequestMapping(value = "/loadAiCustomerDetail")
	public String loadAiCustomerDetail(){
		return "customer/myCustomer/myCustomerdetail/aiEmpDetail";
	}



	/**获取大名单资源信息**/
	@RequestMapping("/list")
	@ResponseBody
	public Map<String, Object> dictList(QueryRequest request, CAiEmp bigEmp, String isBig) {
		MyUser user = this.getCurrentUser();
		return super.selectByPageNumSize(request, () -> this.aiEmpServices.getAllAiEmpServices(bigEmp,request,isBig,user));
	}

	/**校对大名单资源导入的表头**/
	@RequestMapping(value = "/AiEmpValiable",method = RequestMethod.POST)
	@ResponseBody
	public ResponseBo valiableBigEmpResource(String impUrl){
		//读取列术，查看内容，，自动义验证规则
		ResponseBo lis = AIReadExcel.checkExcel(impUrl);
		//校对表头，，自定义校验规则
		return lis;
	}
	/**查询客户的详情**/
	@RequestMapping("/viewAiEmpDetail")
	@ResponseBody
	public ResponseBo viewAiEmpDetail(String keyid){
		MyUser user = this.getCurrentUser();
		return aiEmpServices.findAllAiEmpInfoById(keyid,user);
	}
	/**修改用户得基本信息**/
	@RequestMapping(value = "/aiEmpEditinfo")
	@ResponseBody
	public ResponseBo bigempEditinfo(CAiEmp emp){
		MyUser user = this.getCurrentUser();
		emp.setAiRecent(user.getNickname()+Constant.GENZONG_RECORD_ZILAO);
		emp.setAiRecentTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
		return aiEmpServices.changeAiEmpInfo(emp,user);
	}


	/**AI单初始信息信息导入**/
	@RequestMapping(value = "/AIEmpImport",method = RequestMethod.POST)
	@ResponseBody
	public ResponseBo ImportBigEmpResource(String impUrl,String batch,String director,String bpResType,String isBalan){
		String uuid  = Utils.getUUID();
		Map<String,Object> map = AIReadExcel.createExcel(impUrl,batch,bpResType,uuid,director);
		List<CAiEmp> lis = new ArrayList<>();
		List<EprRecords> errorList = new ArrayList<>();
		//获取正确的导入集合信息
		if(null!=map&&map.containsKey("list")){
			lis = (List<CAiEmp>)map.get("list");
		}

		//获取错误的导入集合信息
		if(null!=map&&map.containsKey("errorList")){
			errorList = (List<EprRecords>)map.get("errorList");
		}
		try {
			MyUser user =  this.getCurrentUser();
			String username = user.getUsername();
			EpRecords records = new EpRecords();
			records.setEpBatch(batch);
			records.setEpDirector(director);
			records.setEpNum(lis.size()+"");
			records.setEpOption(username);
			records.setEpTime(new Date());
			records.setEpType(bpResType);
			records.setEpUuid(Utils.getUUID());
			records.setEpBatchUuid(uuid);
			records.setEpBalanceIsbalan(isBalan);
			records.setEpBalanceNum("0");
			records.setEpBalanceOver("0");

			List<CAiEmp> bigEmps = new ArrayList<>();
			List<EprRecords> allChongfu = new ArrayList<>();

			/**验证数据重复的数据**/
			List<String> listAll = aiEmpServices.getAllAIData();
			/**验证推广资源是不是有重复信息**/
			List<String> listExemp = exEmpServices.getAllExEmpPhone();
			EprRecords epr  = null;
			for (CAiEmp bigEmp1:lis){
				String phone1 = bigEmp1.getAiMobile();
				if (listAll.contains(phone1)){
					epr  = new EprRecords();
					epr.setcEprPhone(bigEmp1.getAiMobile());
					epr.setcEprUser(bigEmp1.getAiName());
					epr.setcEprTime(new Date());
					epr.setcEprBatch(bigEmp1.getAiBatch());
					epr.setcEprBacthUuid(records.getEpUuid());
					epr.setcEprReson("根据手机号查询,当前AI资源已经存在资源");
					epr.setcEprDeng(bigEmp1.getAiGroud());
					epr.setcEprZone(bigEmp1.getAiZone());
					allChongfu.add(epr);
				}else if(listExemp.contains(phone1)){
					epr  = new EprRecords();
					epr.setcEprPhone(bigEmp1.getAiMobile());
					epr.setcEprUser(bigEmp1.getAiName());
					epr.setcEprTime(new Date());
					epr.setcEprBatch(bigEmp1.getAiBatch());
					epr.setcEprBacthUuid(records.getEpUuid());
					epr.setcEprReson("根据手机号查询,当前推广资源已经存在资源");
					epr.setcEprDeng(bigEmp1.getAiGroud());
					epr.setcEprZone(bigEmp1.getAiZone());
					allChongfu.add(epr);
				}else{
					bigEmps.add(bigEmp1);
				}
			}

			if(errorList.size()>0){
				for(EprRecords records1:errorList){
					records1.setcEprBacthUuid(records.getEpUuid());
				}
			}
			allChongfu.addAll(errorList);
			records.setEpFNum(allChongfu.size()+"");
			records.setEpDtype(Constant.ZIYUAN_TYPE_EXEMP);
			int num = 0;
			try {
				num = aiEmpServices.batchInsert(bigEmps,allChongfu,records);
			}catch (Exception e){
				e.printStackTrace();
				return ResponseBo.error("数据导入成功,生成导入记录失败");
			}

			if(lis.size()>0&&allChongfu.size()<1){
				return ResponseBo.ok("noError","导入成功，没有错误和重复数据");
			}else if(lis.size()>0&&allChongfu.size()>0){
				return ResponseBo.ok("hasError",records.getEpUuid());
			}else if(lis.size()==0&&allChongfu.size()>0){
				return ResponseBo.ok("isError",records.getEpUuid());
			}else if(lis.size()==0&&allChongfu.size()==0){
				return ResponseBo.ok("isNull",records.getEpUuid());
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ResponseBo.error("导入失败");
	}
	/**大资源客户导出客户信息的 记录**/
	@RequestMapping("/exportAIEmpDetail")
	@ResponseBody
	public ResponseBo exportBigEmpDetail(String ids,String exportMsg){
		try {
			String name = this.getCurrentUser().getUsername();
			aiEmpServices.exportBigEmpRecords(ids,name,exportMsg);
			return ResponseBo.ok("导出记录成功");
		}catch (Exception e){
			logger.error("AI资源名单导出大资源客户失败："+e.getMessage());
		}
		return ResponseBo.error("导出失败");
	}
	/**删除资源客户信息**/
	@RequestMapping("/deleteAIEmpDetail")
	@ResponseBody
	public ResponseBo deleteAIEmpDetail(String ids){
		if (StringUtils.isEmpty(ids)){
			return ResponseBo.error("参数为空");
		}
		return aiEmpServices.deleteAiEmpResource(ids);
	}
	/**执行分配**/
	@RequestMapping(value = "/bigEmpbatchUpdateByEmp")
	@ResponseBody
	public  ResponseBo bigEmpbatchUpdateByEmp(CAiEmp cAiEmp,String ids){
		MyUser user = this.getCurrentUser();
		String userId  = user.getUserUuid();
		String username = user.getUsername();
		cAiEmp.setAiDisPerson(userId);
		MyUser userFen = userService.findUserByUuids(cAiEmp.getAiDistriute());
		cAiEmp.setAiRecent(user.getNickname()+Constant.GENZONG_RECORD_FENPEI+userFen.getNickname());
		cAiEmp.setAiRecentTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
		return aiEmpServices.executeAIDisfenpei(cAiEmp,ids,username);
	}

	/**查询标签**/
	@RequestMapping("/getAiEmpDetailLabel")
	@ResponseBody
	public ResponseBo getBigEmpDetailLabel(String keyid){
		return aiEmpServices.selectAiEmpLabel(keyid);
	}


	/**大资源客户导出excel**/
	@RequestMapping("/downloadList")
	@ResponseBody
	public ResponseBo downloadList(String uuid){
		try {
			Example example = new Example(EprRecords.class);
			example.createCriteria().andEqualTo("cEprBacthUuid",uuid);
			List<EprRecords> list = recordsMapper.selectByExample(example);
			List<CAiEmpImport> cAiEmpImportList = new ArrayList<>();
			if(list.size()>0){
				for(EprRecords records:list){
					CAiEmpImport empImport = new CAiEmpImport();
					empImport.setCustomer(records.getcEprUser());
					empImport.setMobile(records.getcEprPhone());
					empImport.setZone(records.getcEprZone());
					empImport.setGroup(records.getcEprDeng());
					empImport.setReson(records.getcEprReson());
					cAiEmpImportList.add(empImport);
				}
			}

			ResponseBo responseBo = FileUtils.createExcelByPOIKit("Ai客户资料表", cAiEmpImportList, CAiEmpImport.class);
			return responseBo;
		}catch (Exception e){
			logger.error("导出大资源客户失败："+e.getMessage());
		}
		return ResponseBo.error("导出失败");
	}
}
